package com.etb.wisdom.eframe.org.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.etb.core.pojo.CriteriaType;
import com.etb.core.service.ETBService;
import com.etb.core.utils.DataUtil;
import com.etb.core.utils.SequenceUtil;
import com.etb.wisdom.eframe.auth.AuthConstant.AuthType;
import com.etb.wisdom.eframe.auth.AuthConstant.PartyType;
import com.etb.wisdom.eframe.model.EtbPartyAuth;
import com.etb.wisdom.eframe.model.OrgPosition;
import com.etb.wisdom.eframe.org.service.OrgPositionService;

@Service
public class OrgPositionServiceImpl extends ETBService implements OrgPositionService {
	
	@Override
	public List queryAll(String... args) {
		//TODO 添加数据权限
		return service.queryAll(OrgPosition.class, args);
	}
	
	@Override
	public List<OrgPosition> queryAllOneLevel() {
		CriteriaType criteria = new CriteriaType(OrgPosition.class);
		criteria.addExpr("uplevelid_isnull", null);
		return service.query(criteria);
	}

	@Override
	public List<OrgPosition> queryAllNotOneLevel() {
		CriteriaType criteria = new CriteriaType(OrgPosition.class);
		criteria.addExpr("uplevelid_isnotnull", null);
		return service.query(criteria);
	}

	@Override
	public void save(OrgPosition posi) {
		service.save(posi);
		if(StringUtils.isBlank(posi.getUplevelid())) {
			posi.setPosiseq(posi.getId());
		} else {
			OrgPosition uplevelPosi = new OrgPosition();
			uplevelPosi.setId(posi.getUplevelid());
			service.extend(uplevelPosi);
			posi.setPosiseq(SequenceUtil.generateNewSequence(uplevelPosi.getPosiseq(), posi.getId()));
		}
		service.save(posi);
	}
	
	@Override
	public void saveRole(String posiId, String addRoleIds, String delRoleIds) {
		List<String> addIdList = DataUtil.split(addRoleIds);
		List<String> delIdList = DataUtil.split(delRoleIds);
		for(String id: addIdList) {
			EtbPartyAuth auth = new EtbPartyAuth();
			auth.setPartyid(posiId);
			auth.setPartytype(PartyType.position.toString());
			auth.setAuthid(id);
			auth.setAuthtype(AuthType.role.toString());
			service.save(auth);
		}
		for(String id: delIdList) {
			EtbPartyAuth auth = new EtbPartyAuth();
			auth.setPartyid(posiId);
			auth.setPartytype(PartyType.position.toString());
			auth.setAuthid(id);
			auth.setAuthtype(AuthType.role.toString());
			service.delete(auth);
		}
	}

}
